<?php


namespace App\Messenger\Handler;


use App\DTO\UserInput;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use http\Exception\InvalidArgumentException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

class UserInputHandler implements MessageHandlerInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;
    private $request;

    public function __construct(EntityManagerInterface $entityManager, RequestStack $requestStack)
    {
        $this->entityManager = $entityManager;
        $this->request = $requestStack->getCurrentRequest();
    }

    public function __invoke(UserInput $input)
    {
        // TODO: Implement __invoke() method.
        $methods = $this->request->getMethod();
        if ($methods == 'POST'){
            $user = (new User())
                ->setLoveCode($input->getCode())
                ->setUserName($input->getUserName())
                ->setEmail($input->getEmail())
                ->setPwd($input->getPwd())
            ;

        }
        if ($methods == 'PUT'){
            $id = $this->request->get('id');
            /** @var User $user */
            $user = $this->entityManager->getRepository(User::class)->find($id);
            if (empty($user)){
                throw new NotFoundResourceException('没有找到数据');
            }
            if (!empty($input->getFriend())){
                foreach ($input->getFriend() as $friend){
                    $user->setFriends($friend);
                }

            }
        }
        $this->entityManager->persist($user);
        $this->entityManager->flush();

    }

}
